import json
import logging
import uuid

from utils import db_util
from controller import base_handler


def module_count(system_id, m_code):
    sql = """ select count(*) from  crud_module where system_id=? and m_code=? """
    row = db_util.fetchone(sql, params=[system_id, m_code])
    return row[0]


class ListHandler(base_handler.BaseHandler):
    def get(self):

        page = self.get_query_argument("page", "1")
        perPage = self.get_query_argument("perPage", "100")
        orderBy = self.get_query_argument("orderBy", "m_code")
        orderDir = self.get_query_argument("orderDir", "asc")

        params = []
        where_sql = "where"
        for field_name in ("system_id",):
            field_value = self.get_query_argument(field_name, None)
            if field_value:
                params.append(field_value)
                where_sql += " %s = ? and" % field_name

        for field_name in ("m_code", "m_name", "m_desc",):
            field_value = self.get_query_argument(field_name, None)
            if field_value:
                params.append("%" + field_value + "%")
                where_sql += " %s like ? and" % field_name

        sql = """select cm.*,cs.sys_name from crud_module cm left join crud_system cs on cs.id=cm.system_id """
        if len(params) > 0:
            sql += where_sql[0:-3]
        else:
            params = None

        sql += " order by %s %s" % (orderBy, orderDir)

        rows = db_util.execute_page(sql, int(page), int(perPage), params)
        for row in rows["items"]:
            module_id = row["id"]
            sql = """select count(*) from crud_resource  where module_id=? """
            tmp_row = db_util.fetchone(sql, [module_id])
            row["resource_count"] = tmp_row[0]
            sql = """select count(*) from crud_interface  where module_id=? """
            tmp_row = db_util.fetchone(sql, [module_id])
            row["interface_count"] = tmp_row[0]
        res = {"status": 0, "message": "ok",
               "data": {"page": page, "total": rows["total"], "rows": rows["items"]}}

        self.set_response(res, 200)


class SelectHandler(base_handler.BaseHandler):
    def get(self):
        system_id = self.get_query_argument("system_id", None)
        if system_id is None:
            res = {"status": 0, "message": "ok", "data": {"options": []}}
            self.set_response(res, 200)
            return

        sql = """select id,m_name,m_code from crud_module where system_id=? order by m_code """

        rows = db_util.fetchall(sql, [system_id])
        options = []
        for row in rows:
            options.append({"value": row[0], "label": row[1], "m_code": row[2]})

        res = {"status": 0, "message": "ok", "data": {"options": options}}

        self.set_response(res, 200)


class AddHandler(base_handler.BaseHandler):
    def post(self):
        logging.info(self.request.body.decode())
        req_body = json.loads(self.request.body.decode())

        m_id = uuid.uuid1().hex
        system_id = req_body.get("system_id", None)
        m_code = req_body.get("m_code", None)
        m_name = req_body.get("m_name", None)
        m_desc = req_body.get("m_desc", None)

        count = module_count(system_id, m_code)
        if count > 0:
            res = {"status": 1, "message": "添加失败：模块编号重复[%s]" % m_code}
            self.set_response(res, 200)
            return

        sql = """ insert into crud_module (id,system_id,m_code,m_name,m_desc)values(?,?,?,?,?)"""
        param = [m_id, system_id, m_code, m_name, m_desc]
        flag = db_util.execute_update(sql, params=param)
        if flag is True:
            res = {"status": 0, "message": "添加成功"}
        else:
            res = {"status": 1, "message": "添加失败:%s" % db_util.get_last_error()}

        self.set_response(res, 200)


class EditHandler(base_handler.BaseHandler):
    def post(self):
        logging.info(self.request.body.decode())
        req_body = json.loads(self.request.body.decode())
        m_id = req_body.get("id", None)
        param = []
        up_sql = ""
        for field_name in ("m_code", "m_name", "m_desc",):
            field_value = req_body.get(field_name, None)
            if field_value:
                param.append(field_value)
                up_sql += "%s=?," % field_name
        param.append(m_id)

        sql = """update crud_module set %s where id=?""" % (up_sql[0:-1])
        flag = db_util.execute_update(sql, param)
        if flag is True:
            res = {"status": 0, "message": "修改成功"}
        else:
            res = {"status": 1, "message": "修改失败:%s" % db_util.get_last_error()}

        self.set_response(res, 200)


class DelHandler(base_handler.BaseHandler):
    def post(self):
        logging.info(self.request.body.decode())
        req_body = json.loads(self.request.body.decode())
        flag = False
        m_id = req_body.get("id", None)

        if m_id and m_id != "":
            sql = "delete from crud_resource where module_id=?"
            db_util.execute_update(sql, [m_id])

            sql = "delete from crud_verify where interface_id in (select id from crud_interface where module_id =?)"
            db_util.execute_update(sql, [m_id])

            sql = "delete from crud_interface where module_id=?"
            db_util.execute_update(sql, [m_id])

            sql = "delete from crud_module where id =?"
            flag = db_util.execute_update(sql, [m_id])
        if flag is True:
            res = {"status": 0, "message": "删除成功"}
        else:
            res = {"status": 1, "message": "删除失败:%s" % db_util.get_last_error()}

        self.set_response(res, 200)
